package main

import (
	"context"
	pb "monthly/kitex_gen/monthly/wallet"
	"monthly/rpc/basic/global"
	"monthly/rpc/basic/model"
)

// WalletServiceImpl implements the last service interface defined in the IDL.
type WalletServiceImpl struct{}

// Recharge implements the WalletServiceImpl interface.
func (s *WalletServiceImpl) Recharge(ctx context.Context, req *pb.RechargeReq) (*pb.RechargeResp, error) {
	// TODO: Your code here...
	var passenger model.Passenger
	if err := global.DB.Debug().Where("id = ?", req.PId).Limit(1).Find(&passenger).Error; err != nil {
		return &pb.RechargeResp{
			Code:    301,
			Message: "查询失败",
		}, nil
	}
	if passenger.Id == 0 {
		return &pb.RechargeResp{
			Code:    404,
			Message: "用户不存在",
		}, nil
	}
	record := model.RechargeRecord{
		PId:              int64(req.PId),
		RechargeAmount:   req.RechargeAmount,
		RechargeChannels: req.RechargeChannels,
	}
	if err := global.DB.Debug().Create(&record).Error; err != nil {
		return &pb.RechargeResp{
			Code:    503,
			Message: "服务器异常",
		}, nil
	}
	wallet := model.PWallet{}
	wallet.Balance = wallet.Balance + req.RechargeAmount
	global.DB.Updates(&wallet)
	return &pb.RechargeResp{
		Code:    200,
		Message: "充值成功",
	}, nil
}

// Withdrawal implements the WalletServiceImpl interface.
func (s *WalletServiceImpl) Withdrawal(ctx context.Context, req *pb.WithdrawalReq) (*pb.WithdrawalResp, error) {
	// TODO: Your code here...
	var passenger model.Passenger
	if err := global.DB.Debug().Where("id = ?", req.PId).Limit(1).Find(&passenger).Error; err != nil {
		return &pb.WithdrawalResp{
			Code:    301,
			Message: "查询失败",
		}, nil
	}
	if passenger.Id == 0 {
		return &pb.WithdrawalResp{
			Code:    404,
			Message: "用户不存在",
		}, nil
	}
	wallet := model.PWallet{}
	if wallet.Balance < req.WithdrawalAmount {
		return &pb.WithdrawalResp{
			Code:    301,
			Message: "金额不足",
		}, nil
	}
	withdrawal := model.PWithdrawal{
		PId:                int64(req.PId),
		WithdrawalAmount:   req.WithdrawalAmount,
		WithdrawalChannels: req.WithdrawalChannels,
	}
	if err := global.DB.Debug().Create(&withdrawal).Error; err != nil {
		return &pb.WithdrawalResp{
			Code:    503,
			Message: "服务器异常",
		}, nil
	}
	wallet.Balance = wallet.Balance - req.WithdrawalAmount
	global.DB.Updates(&wallet)
	return &pb.WithdrawalResp{
		Code:    200,
		Message: "提现成功",
	}, nil
}
